package com.whut.whw.post;


import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.whut.whw.R;
import com.whut.whw.base.BaseActivity;
import com.whut.whw.login.LoginActivity;
import com.whut.whw.model.BackResult;
import com.whut.whw.util.BackResultCallback;
import com.whut.whw.util.ImageViewUtils;
import com.whut.whw.util.InputUtils;
import com.whut.whw.util.LogUtils;
import com.whut.whw.util.SnackerbarUtils;
import com.whut.whw.util.ToastUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import butterknife.BindView;
import okhttp3.Call;

import static com.whut.whw.constant.ConfigConsts.BASE_URL;
import static android.R.attr.id;

/**
 * Created by 张芳容 on 2017/06/08.
 */
public class PostGoodActivity extends BaseActivity {

    private String pathImage;
    private Bitmap bmp;  //导入临时图片
    private ArrayList<HashMap<String, Object>> imageItem;
    private ArrayList<String> imagePaths;
    private SimpleAdapter simpleAdapter;     //适配器
    private static final int REQUEST_SELECT_ProCity_CODE = 100;
    private static final int REQUEST_SELECT_GOODS_TYPE_CODE = 200;
    private String[] numsString = new String[]{"一", "二", "三", "四", "五", "六", "七", "八", "九"};

    //物品类别
    private String goods_TypeBM;

    //tc
    @BindView(R.id.toolbar)
    Toolbar toolbar;

    @BindView(R.id.good_title)
    EditText good_title;//标题

    @BindView(R.id.good_detail)
    EditText good_detail;//描述内容

    @BindView(R.id.good_add_picture)
    PostGridView good_add_picture;//选择的图片

    @BindView(R.id.old_new_tv)
    TextView old_new_tv;//新旧程度

    @BindView(R.id.old_new_seekbar)
    SeekBar old_new_seekbar;//新旧程度seekbar

    @BindView(R.id.good_price)
    EditText good_price;//我的估价

    @BindView(R.id.good_class)
    TextView good_class;//物品类别

    @BindView(R.id.good_area)
    TextView good_area;//所在地区

    //****************
    @BindView(R.id.wantLayout)
    LinearLayout wantLayout;
    @BindView(R.id.add_want)
    ImageButton add_want;//我想换的加号图片按钮

    //想要交换的物品
    @BindView(R.id.good_change1)
    TextView good_change1;
    @BindView(R.id.good_change2)
    TextView good_change2;
    @BindView(R.id.good_change3)
    TextView good_change3;

    @BindView(R.id.sale_change_radiogroup)
    RadioGroup sale_change_radiogroup;//交易类型
    @BindView(R.id.sale_want_layout)
    LinearLayout sale_want_layout;//我想换界面

    @Override
    public int getLayoutId() {
        return R.layout.activity_post_goods;
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        imageItem = new ArrayList<HashMap<String, Object>>();
        imagePaths = new ArrayList<String>();
        initToolbar();
        try {
            initGridView();
        } catch (Exception e) {
            LogUtils.e("初始化错误", e.toString());
        }
        //输入控制
        InputUtils.setEditTextFloat(good_price, 8, 1);
        /**
         * *********************************************************
         * * 未来会需要用到的https://github.com/LuckSiege/PictureSelector#%E5%8A%9F%E8%83%BD%E9%85%8D%E7%BD%AE
         * * 包括裁剪和压缩后的缓存，要在上传成功后调用，
         * * 注意：需要系统sd卡权限
         * * PictureFileUtils.deleteCacheDirFile(MainActivity.this);
         * *********************************************************
         */
    }


    /**
     * 初始化工具栏
     */
    private void initToolbar() {
        toolbar.inflateMenu(R.menu.activity_post_menu);
        toolbar.setNavigationIcon(R.drawable.rc_back_icon);
        toolbar.setTitle(R.string.good_title);
        toolbar.setTitleTextColor(ContextCompat.getColor(context, R.color.white));
    }

    /**
     * 初始化照片
     */
    private void initGridView() {
        // ToastUtils.showShort("初始化GridView");
        bmp = BitmapFactory.decodeResource(getResources(), R.drawable.add_picture); //加号
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("itemImage", bmp);
        imageItem.add(map);
        imagePaths.add("null");//设置添加图片路径为空
        add_image_to_GridView();
    }

    @Override
    public void setListener() {
        //选择省市
        good_area.setOnClickListener(new Select_area_listener());
        //动态添加文本框
        add_want.setOnClickListener(new Add_want_listener());
        //点击图片事件（增加。删除。查看大图）
        good_add_picture.setOnItemClickListener(new Add_pic_listener());
        good_add_picture.setOnItemLongClickListener(new Delete_Item_listener());
        good_class.setOnClickListener(new Select_class_listener());
        //选中交换类型事件监听
        sale_change_radiogroup.setOnCheckedChangeListener(new Sale_change_Listener());
        //返回
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PostGoodActivity.this.finish();
            }
        });
        toolbar.setOnMenuItemClickListener(new MenuItemSelectedListener());
        //seekbar监听
        old_new_seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                //进度发生改变时会触发
                if (progress == 10) {
                    old_new_tv.setText("全新");
                } else if (progress == 0) {
                    old_new_seekbar.setProgress(1);
                } else {
                    old_new_tv.setText(numsString[progress - 1] + "成新");
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                //按住SeekBar时会触发
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                //放开SeekBar时触发
            }
        });
    }

    /**
     * 添加想要物品的标签的监听事件
     */
    class Add_want_listener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            if (good_change2.getVisibility() == View.INVISIBLE) {
                good_change2.setVisibility(View.VISIBLE);
            } else if (good_change3.getVisibility() == View.INVISIBLE) {
                good_change3.setVisibility(View.VISIBLE);
            } else {
                ToastUtils.showShort("对不起，您最多只能输入3个意愿");
                return;
            }
        }
    }

    /**
     * 选择省市监听事件
     */
    class Select_area_listener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            // ToastUtils.showShort("点击了选择地址按钮");
            Intent intent = new Intent(PostGoodActivity.this, AreaSelectActivity.class);
//            intent.setClass(s);
            startActivityForResult(intent, REQUEST_SELECT_ProCity_CODE);
        }
    }

    /**
     * 选择照片
     */
    class Add_pic_listener implements AdapterView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            //判断最后一项是否是加号图片
            if (position == (imageItem.size() - 1) && "null".equals(imagePaths.get(imagePaths.size() - 1))) { //点击图片位置为+ 0对应0张图片
                int i = 9;
                if (imageItem != null) {
                    i = 10 - imageItem.size();//剩余几张
                }
                PictureSelector.create(PostGoodActivity.this)
                        .openGallery(PictureMimeType.ofImage())
                        .maxSelectNum(i)
                        .imageSpanCount(3)
                        .selectionMode(PictureConfig.MULTIPLE)
                        .previewImage(true)
                        .isCamera(true)
                        .setOutputCameraPath("/whw/")
                        .forResult(PictureConfig.CHOOSE_REQUEST);
            } else {//如果不是则可以查看大图
                Intent intent = new Intent(PostGoodActivity.this, ShowPicActivity.class);
                Bundle bundle = new Bundle();
                bundle.putInt("position", position);
                bundle.putStringArrayList("imagePaths", imagePaths);
                //再把bundle中的数据传给intent，以传输过去
                intent.putExtras(bundle);
                //  ToastUtils.showShort("点击了显示图片按钮");
                startActivity(intent);
            }
        }
    }

    /**
     * 长按删除照片
     */
    class Delete_Item_listener implements AdapterView.OnItemLongClickListener {

        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            //判断最后一项是否是加号图片
            if (!"null".equals(imagePaths.get(position))) {
                dialog_Delete_Pic(position);
                return true;
            }
            return false;
        }
    }

    /**
     * 选择物品类别
     */
    class Select_class_listener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            //ToastUtils.showShort("您点击了选择物品分类按钮");
            Intent intent = new Intent(PostGoodActivity.this, Goods_typeSelectActivity.class);
//            intent.setClass(s);
            startActivityForResult(intent, REQUEST_SELECT_GOODS_TYPE_CODE);
        }
    }

    /**
     * 返回结果
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null) {//如果有返回结果
            switch (requestCode) {
                //获取省市
                case REQUEST_SELECT_ProCity_CODE:
                    Bundle bundle = data.getExtras();
                    String province = bundle.getString("province");
                    String city = bundle.getString("city");
                    //good_areaID = bundle.getString("zipCode");
                    String temp = "";
                    if (province.equals(city))
                        temp = city;
                    else
                        temp = province + city;
                    good_area.setText(temp);
                    break;
                //获取照片
                case PictureConfig.CHOOSE_REQUEST:
                    List<LocalMedia> list = PictureSelector.obtainMultipleResult(data);
                    for (int i = 0; i < list.size(); i++) {
                        LogUtils.e("获取的照片", i + " " + list.get(i).getPath());
                        HashMap<String, Object> map = new HashMap<String, Object>();
                        map.put("itemImage", BitmapFactory.decodeFile(list.get(i).getPath()));
                        imageItem.add(0, map);
                        imagePaths.add(0, list.get(i).getPath());
                    }
                    if (imageItem.size() == 10) {
                        imageItem.remove(imageItem.size() - 1);
                        imagePaths.remove(imagePaths.size() - 1);
                    }
                    add_image_to_GridView();
                    break;
                //获取物品类别
                case REQUEST_SELECT_GOODS_TYPE_CODE:
                    Bundle bundle_goodstype = data.getExtras();
                    String first = bundle_goodstype.getString("first");
                    String second = bundle_goodstype.getString("second");
                    goods_TypeBM = bundle_goodstype.getString("code");
                    good_class.setText(second);
                    break;
            }

        }
    }


    private Pattern intPattern = Pattern.compile("^[-\\+]?[\\d]*\\.0*$");

    public String getString(Map map, String key, String defaultValue) {
        Object obj = map.get(key);
        return obj == null ? defaultValue : (obj instanceof Number && intPattern.matcher(obj.toString()).matches() ? String.valueOf(Long.valueOf(((Number) obj).longValue())) : obj.toString());
    }

    private EditText getEditText() {
        AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        EditText editText = new EditText(PostGoodActivity.this);
        editText.setLayoutParams(lp);
        editText.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
        editText.setPadding(80, 0, 0, 0);
        editText.setTextSize(R.dimen.text_size_medium);
        editText.setBackgroundResource(R.drawable.edittext_bg);
        return editText;
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    /**
     * 向GridView中添加照片
     */
    private void add_image_to_GridView() {
        simpleAdapter = new SimpleAdapter(this,
                imageItem, R.layout.griditem_addpic,
                new String[]{"itemImage"}, new int[]{R.id.imageView1});
        simpleAdapter.setViewBinder(new SimpleAdapter.ViewBinder() {
            @Override
            public boolean setViewValue(View view, Object data,
                                        String textRepresentation) {
                // TODO Auto-generated method stub
                if (view instanceof ImageView && data instanceof Bitmap) {
                    ImageView i = (ImageView) view;
                    //ToastUtils.showShort(String.valueOf(i.getHeight()),String.valueOf(i.getWidth()));
                    Bitmap bitmap = ImageViewUtils.createFitBitmap(960, 960, (Bitmap) data);
                    i.setImageBitmap(bitmap);
                    return true;
                }
                return false;
            }
        });
        good_add_picture.setAdapter(simpleAdapter);
        simpleAdapter.notifyDataSetChanged();
    }

    /**
     * Dialog对话框提示用户删除操作
     * position为删除图片位置
     *
     * @param position
     */
    protected void dialog_Delete_Pic(final int position) {
        AlertDialog.Builder builder = new AlertDialog.Builder(PostGoodActivity.this);
        builder.setMessage("确认移除已添加图片吗？");
        builder.setTitle("提示");
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                imageItem.remove(position);
                imagePaths.remove(position);
                //如果最后一项不是null则添加一个加号图片
                if (!"null".equals(imagePaths.get(imagePaths.size() - 1))) {
                    initGridView();
                }
                add_image_to_GridView();
                simpleAdapter.notifyDataSetChanged();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    private class Sale_change_Listener implements RadioGroup.OnCheckedChangeListener {
        @Override
        public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
            if (checkedId == R.id.radio_only_sale) {
                sale_want_layout.setVisibility(View.GONE);
            } else {
                sale_want_layout.setVisibility(View.VISIBLE);
            }
        }
    }

    /**
     * 点击发布菜单的事件
     */
    private class MenuItemSelectedListener implements Toolbar.OnMenuItemClickListener {
        /**
         * @param item
         * @return
         */
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            SharedPreferences sp = getSharedPreferences("userinfo", MODE_PRIVATE);
            String userID = sp.getString("yhbh", "");
            if("".equals(userID)){
                ToastUtils.showShort("您尚未登录，请先登录");
                Intent intent = new Intent(PostGoodActivity.this, LoginActivity.class);
                startActivity(intent);
            }else{
                String title = good_title.getText().toString();//标题
                String content = good_detail.getText().toString();//内容
                String oldlevel = String.valueOf(old_new_seekbar.getProgress());//新旧程度
                String price = good_price.getText().toString();//我的估价
                String goodsType = goods_TypeBM == null ? "" : goods_TypeBM;//物品类别
                String area = good_area.getText().toString();//所在地区（填写文字）
                String changeType = "";//交易类型
                for (int i = 0; i < sale_change_radiogroup.getChildCount(); i++) {
                    RadioButton radioButton = (RadioButton) sale_change_radiogroup.getChildAt(i);
                    if (radioButton.isChecked()) {
                        changeType = radioButton.getTag().toString();
                        break;
                    }
                }
                String want_change = "";//我想换（用分号隔开）
                for (int i = 0; i < wantLayout.getChildCount(); i++) {
                    EditText editText = (EditText) wantLayout.getChildAt(i);
                    String temp = editText.getText().toString().trim();
                    if (!"".equals(temp)) {
                        want_change += temp + ";";
                    }
                }
                //物品类别必填
                if ("".equals(goodsType.trim())) {
                    ToastUtils.showShort("请选择物品类别");
                    return false;
                }
                //检查输入是否合法（标题和详情不能为空）
                if ("".equals(title.trim()) || "".equals(content.trim())) {
                    ToastUtils.showShort("物品标题和简介不能为空");
                    return false;
                }
                //发送发布请求
                String url = BASE_URL + "postGoods/postgood";
                //普通参数
                Map<String, String> params = new HashMap<>();
                params.put("userID", userID);
                params.put("title", title);
                params.put("content", content);
                params.put("oldlevel", oldlevel);
                params.put("price", price);
                params.put("goodsType", goodsType);
                params.put("area", area);
                params.put("changeType", changeType);
                params.put("want_change", want_change);

                PostFormBuilder postFormBuilder = OkHttpUtils.post();
                postFormBuilder.url(url);
                //图片
                String path = "";
                String name = "";
                for (int i = 0; i < imagePaths.size(); i++) {
                    if (!"null".equals(imagePaths.get(i))) {
                        String fullName = imagePaths.get(i);
                        int index = fullName.lastIndexOf('/');
                        path = fullName.substring(0, index);
                        name = fullName.substring(index + 1);
                        LogUtils.e("文件路径", "完整路径" + fullName + "路径->" + path + "名字->" + name);
                        File file = new File(fullName);
                        if (!file.exists()) {
                            ToastUtils.showLong("文件不存在，请修改文件路径");
                            return false;
                        }
                        postFormBuilder.addFile("multipartFile", name, file);
                    }
                }

                postFormBuilder.params(params).build().execute(new BackResultCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        getUiDelegate().toastLong(e.toString());
                        Log.e("发布物品", e.toString());
                    }

                    @Override
                    public void onResponse(BackResult response, int id) {
                        ToastUtils.showLong(response.getMsg());
                        finish();
                    }
                });

            }
            return false;
        }
    }
}
